package net.println.kotlin.chapter3

fun main(args: Array<String>) {
    println("请输入计算式，如 3 + 4")
    val input = readLine()
    if (input != null) {
        val split = input.split(" ")
        val arg1 = split[0].toDouble()
        val op = split[1]
        val arg2 = split[2].toDouble()
        println("$arg1 $op $arg2 = ${Operator(op).apply(arg1,arg2)}")
    }
}

class Operator(op: String) {
    val opFun: (left: Double, right: Double) -> Double

    init {
        opFun = when (op) {
            "+" -> { l, r -> l + r }
            "-" -> { l, r -> l - r }
            "*" -> { l, r -> l * r }
            "/" -> { l, r -> l / r }
            else -> throw UnsupportedOperationException(op)
        }
    }

    fun apply(left: Double, right: Double): Double {
        return opFun(left, right)
    }
}